package com.xuecheng.auth.domain.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.auth.domain.feginclient.CheckCodeServiceClient;
import com.xuecheng.auth.domain.model.dto.CheckCodeVerifyDto;
import com.xuecheng.auth.domain.model.dto.XcUserDto;
import com.xuecheng.auth.domain.model.entity.XcUser;
import com.xuecheng.auth.domain.model.vo.req.AuthParamsQuery;
import com.xuecheng.auth.domain.service.XcUserService;
import com.xuecheng.auth.domain.strategy.AuthContext;
import com.xuecheng.base.exception.XueChengPlusException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-07  10:35
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserService xcUserService;

    @Autowired
    private CheckCodeServiceClient checkCodeServiceClient;

    /**
     * @param s 账号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) {
        AuthParamsQuery params;
        try {
            params = JSONUtil.toBean(s, AuthParamsQuery.class);
        } catch (Exception e){
            log.error("参数不一致, {}", e.getMessage());
            throw new XueChengPlusException("参数不一致");
        }

        AuthContext authContext = new AuthContext(params);
        XcUserDto xcUserDto = authContext.handleAuth();

        return getUserPrincipal(xcUserDto);
    }

    private UserDetails getUserPrincipal(XcUserDto xcUserDto) {
        // todo 模拟权限
        String[] authorities = {"test"};
        String password = xcUserDto.getPassword();
        xcUserDto.setPassword(null);

        return User.withUsername(JSONUtil.toJsonStr(xcUserDto))
                .password(password)
                .authorities(authorities)
                .build();
    }
}
